from flask import Blueprint,request,jsonify
from werkzeug.sansio.response import Response
from utils.db import db
from utils.comm import get_data
import json
import  time


bp_user = Blueprint('adminuser',__name__)


#角色添加 展示
@bp_user.route('/rolesadd/',methods=['POST','GET'])
def rolesadd():
    if request.method =="POST":
        data = get_data()
        if data['name']:
            sql = "insert into roles values(0,'%s')"%data['name']
            try:
                db.insert(sql)
                return jsonify({"code":200,'msg':'添加成功'})
            except:
                return jsonify({"code":20020,'msg':'角色重复，请重新添加'})
        
    elif request.method == 'GET':
        #获取角色
        sql = "select id,name from roles"
        res = db.find_all(sql)
        return jsonify({"code":200,'list':res})
    

#资源的添加  展示
@bp_user.route('/resourcesadd/',methods=["POST",'GET'])
def resourcesadd():
    if request.method =="POST":
        data = get_data()
        if data:
            sql = "insert into resources values(0,'%s','%s')"%(data['name'],data['url'])
            try:
                db.insert(sql)
                return jsonify({"code":200,'msg':'添加成功'})
            except:
                return jsonify({"code":20020,'msg':'资源重复，请重新添加'})
    elif request.method == 'GET':
        #获取资源信息
        sql = "select id,name from resources"
        res = db.find_all(sql)
        return jsonify({"code":200,'list':res})

#权限分配
@bp_user.route('/perass/',methods=['POST',"GET"])
def perass():
    #权限的分配
    if request.method =="POST":
        pass
        data = get_data()  
        #先删除原来存在的数据
        sql = "delete from roles_resource where roles_id=%d "%(int(data['roles']))
        db.delete(sql)
        ids = data['ids']
        for i in ids:
            
            sql1 ="insert into roles_resource(`roles_id`,`resources_id`) values(%d,%d)"%(int(data['roles']),i)
            db.insert(sql1)
        return jsonify({'code':200,'msg':'资源权限添加成功'})
    elif request.method == 'GET':
        id =request.args.get('id')
        sql = "select `resources_id` from roles_resource where roles_id=%d"%(int(id))
        res = db.find_all(sql)
        list = []
        for i in res:
            list.append(i['resources_id'])
        return jsonify({"code":200,'list':list})

#登录
@bp_user.route('/loginM/',methods=['POST','GET'])
def loginM():
    if request.method =="POST":
        data = get_data()
        sql1 = "select * from admin_user where name='%s'" %data['mobile']
        res = db.find_one(sql1)
        if res:
            return jsonify({'code':20020})
        else:
            sql = "insert into admin_user(name,role_id) values('%s',%d)"%(data['mobile'],int(data['role']))
            print(sql)
            db.insert(sql)
            return jsonify({"code":200,'msg':'登录成功'})
    else:
        pass




